package cc.yugu.yhdw.webserver.service.hdw;

import cc.yugu.yhdw.common.domain.basic.Role;
import cc.yugu.yhdw.common.domain.hdw.BigContent;
import cc.yugu.yhdw.common.domain.hdw.CabinetStrategy;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.common.entity.tree.Node;
import cc.yugu.yhdw.common.entity.tree.NodeModel;
import cc.yugu.yhdw.common.utils.YhdwUtils;
import cc.yugu.yhdw.webserver.biz.client.ClientBizUtils;
import cc.yugu.yhdw.webserver.config.AppConfig;
import cc.yugu.yhdw.webserver.persistence.hdw.BigContentMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.CabinetMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.CabinetStrategyMapper;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 终端策略业务
 * 
 * @Date:Created in 2018/7/7 11:31
 * @Author:
 * @Modified By: zjn 2018/7/7 11:31
 */ 
@Service
public class CabinetStrategyService {
    @Autowired
    CabinetStrategyMapper cabinetStrategyMapper;
    @Autowired
    BigContentMapper bigContentMapper;
    @Autowired
    AppConfig appConfig;
    @Autowired
    CabinetMapper cabinetMapper;
    /**
    * 按主键查询
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.hdw.CabinetStrategy
    * @Author By: zjn 2018/7/7  11:31
    */ 
    public CabinetStrategy find(int id) {
        return cabinetStrategyMapper.find(id);
    }
    /**
    * 按运营商id和代理商id有序查询
    * 
    * @Param: [agentId, agencyId]
    * @Return: java.util.List<cc.yugu.yhdw.common.domain.hdw.CabinetStrategy>
    * @Author By: zjn 2018/7/7  11:32
    */ 
    public List<CabinetStrategy> findByAgency(Integer agentId, Integer agencyId) {
        return cabinetStrategyMapper.findByAgency(agentId, agencyId);
    }
    /**
    * 输出目录树
    * 
    * @Param: [agentId, agencyId, stream]
    * @Return: void
    * @Author By: zjn 2018/7/7  11:37
    */ 
    public void tree(Integer agentId, Integer agencyId, OutputStream stream) throws IOException {

        List<CabinetStrategy> list =  cabinetStrategyMapper.findByAgency(agentId, agencyId);
        List<Node<NodeModel>> roots = new ArrayList<Node<NodeModel>>();
        for(CabinetStrategy cabinetStrategy : list) {
            NodeModel nodeModel = new NodeModel();
            Node<NodeModel> root = new Node<NodeModel>(nodeModel);
            nodeModel.setId(cabinetStrategy.getId());
            nodeModel.setName(cabinetStrategy.getStrategyName());
            roots.add(root);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        JsonGenerator json = objectMapper.getJsonFactory().createJsonGenerator(stream, JsonEncoding.UTF8);
        json.writeStartArray();
        YhdwUtils.writeJson(roots, json);
        json.writeEndArray();
        json.flush();
        json.close();
    }
    /**
    * 分页查询
    * 
    * @Param: [search]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/7  11:37
    */ 
    public Page findPage(CabinetStrategy search) {
        Page page = search.buildPage();
        page.setTotalItems(cabinetStrategyMapper.findPageCount(search));
        search.setBeginIndex(page.getOffset());
        page.setResult(cabinetStrategyMapper.findPageResult(search));
        return page;
    }
    /**
    * 往数据库（2个）插入
    * 
    * @Param: [entity, content]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:37
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult create(CabinetStrategy entity, String content) {
        try {
            // 设置策略版本
            entity.setVersion(1);
            entity.setCreateTime(new Date());
            cabinetStrategyMapper.insert(entity);
            BigContent bigContent = new BigContent();
            bigContent.setId(entity.getId());
            // 设置终端策略类型
            bigContent.setType(BigContent.Type.CABINET_STRATEGY.getValue());
            bigContent.setContent(content);
            // 插入 终端策略类型、主键、详情
            bigContentMapper.insert(bigContent);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();

    }
    /**
    * 更新
    * 
    * @Param: [entity, content]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:55
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult update(CabinetStrategy entity, String content) {
        try {
            // 更新终端策略名称、代理商id、版本
            cabinetStrategyMapper.update(entity);

            BigContent bigContent = new BigContent();
            bigContent.setId(entity.getId());
            bigContent.setType(BigContent.Type.CABINET_STRATEGY.getValue());
            bigContent.setContent(content);
            if (bigContentMapper.update(bigContent) == 0) {
                bigContentMapper.insert(bigContent);
            }

            ClientBizUtils.noticeStrategyChanged(appConfig, entity.getId());
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 删除终端策略前，判断是否被换电柜使用
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  11:56
    */ 
    private ExtResult hasRef(int id) {
        // 查询换电柜主键
        String cabinetCode = cabinetMapper.hasRecordByProperty("strategyId", id);
        if (StringUtils.isNotEmpty(cabinetCode)) {
            return ExtResult.failResult(String.format("该策略已被终端[%s]使用,不能删除", cabinetCode));
        }
        return ExtResult.successResult();
    }
    /**
    * 删除 终端策略
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/7  12:03
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult delete(int id) {
       /* ExtResult result = hasRef(id);
        if(!result.isSuccess()) {
            return result;
        }*/
        bigContentMapper.delete(BigContent.Type.CABINET_STRATEGY.getValue(), id);
        int count =cabinetStrategyMapper.delete(id);
        if (count==0){
            return ExtResult.failResult("删除失败");
        }
        return ExtResult.successResult();
    }
}
